package com.wx.handler.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wx.common.WrapMapper;
import com.wx.constants.Constants;
import com.wx.constants.RedisKeyPrefix;
import com.wx.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>Title:      CustomerLogoutSuccessHandler. </p>
 * <p>Description 默认的退出成功处理器 </p>
 * <p>Copyright: Copyright (c) 2016</p>
 * <p>Company:    医百科技有限公司 </p>
 *
 * @author         <a href="xinglinglove1029@163.com"/>杨文生</a>
 * @since      2020/9/18 20:32
 */
@Component("customerLogoutSuccessHandler")
@Slf4j
public class CustomerLogoutSuccessHandler implements LogoutSuccessHandler {

    private final ObjectMapper objectMapper = new ObjectMapper();


    @Resource
    private RedisService redisService;


    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException {
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (StringUtils.isNotBlank(token) && token.startsWith(Constants.BEARER_AUTHENTICATION)) {
            token = token.replace(Constants.BEARER_AUTHENTICATION, "");
            redisService.remove(RedisKeyPrefix.ONLINEUSER + token);
            log.info("退出成功,token={}",token);
        }
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(WrapMapper.ok("退出成功")));
    }

}
